<template>
  <div>
    <el-button type="primary" @click="onAdd">添加</el-button>
    <el-table :data="newsList">
      <el-table-column label="序号" width="100">
        <template slot-scope="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column prop="title" label="岗位"></el-table-column>
      <el-table-column prop="time" label="发布时间"></el-table-column>
      <el-table-column prop="department" label="部门/位置"></el-table-column>
      <el-table-column width="200" label="操作">
        <template slot-scope="scope">
          <el-button @click="onEdit(scope)" type="text">
            编辑
          </el-button>
          <el-button @click="onDelete(scope)" type="text">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="position:absolute;bottom:100px"
      background
      layout="prev, pager, next"
      :total="total"
      :page-size="pageSize"
      @current-change="onCurrentChange"
    >
    </el-pagination>
    <el-dialog
      :visible.sync="showDialog"
      title="新闻"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="language">
          <el-select v-model="form.language">
            <el-option
              v-for="(item, key) in languages"
              :key="key"
              :label="item"
              :value="Number(key)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="subTitle">
          <el-input v-model="form.subTitle"></el-input>
        </el-form-item>
        <el-form-item label="detail">
          <quill-editor
            class="editor"
            ref="myTextEditor"
            v-model="form.detail"
            :options="editorOption"
            @change="onEditorChange"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
          />
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="onSave">保存</el-button>
      <el-dialog
        width="700px"
        title="上传文件"
        append-to-body
        :visible.sync="showUploadDialog"
      >
        URL：<el-input
          style="width:90%"
          placeholder="请输入文件的url"
          v-model="fileUrl"
        ></el-input>
        <el-upload
          style="display:inline-block"
          action="string"
          :show-file-list="false"
        >
          <el-button style="margin:20px 20px 0 0;">
            上传
          </el-button>
        </el-upload>
        <el-button
          @click="onConfirmInsertFile"
          style="margin:20px 20px 0 0;float:right"
          type="primary"
        >
          确认
        </el-button>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import UploadImage from "../../components/UploadImage.vue";
import {
  apiAddMessage,
  apiGetMessageList,
  apiUpdateMessage,
  apiDeleteMessage,
  apiUploadImage,
} from "@/api/admin";
export default {
  name: "NewsList",
  components: { UploadImage },
  data() {
    let self = this;
    return {
      uploadType: "image",
      fileUrl: "",
      insertPosition: -1,
      languages: { 1: "中文", 2: "英文" },
      showUploadDialog: false,
      isBrowser: process.title === "browser",
      content: `
          <h1 class="ql-align-center"><span class="ql-font-serif" style="background-color: rgb(240, 102, 102); color: rgb(255, 255, 255);"> I am snow example! </span></h1><p><br></p><p><span class="ql-font-serif">W Can a man still be brave if he's afraid? That is the only time a man can be brave. </span></p><p><br></p><p><strong class="ql-font-serif ql-size-large">Courage and folly is </strong><strong class="ql-font-serif ql-size-large" style="color: rgb(230, 0, 0);">always</strong><strong class="ql-font-serif ql-size-large"> just a fine line.</strong></p><p><br></p><p><u class="ql-font-serif">There is only one God, and his name is Death. And there is only one thing we say to Death: "Not today."</u></p><p><br></p><p><em class="ql-font-serif">Fear cuts deeper than swords.</em></p><p><br></p><pre class="ql-syntax" spellcheck="false"><span class="hljs-keyword">const</span> a = <span class="hljs-number">10</span>;
          <span class="hljs-keyword">const</span> editorOption = { <span class="hljs-attr">highlight</span>: <span class="hljs-function"><span class="hljs-params">text</span> =&gt;</span> hljs.highlightAuto(text).value };</pre><p><br></p><p><span class="ql-font-serif">Every flight begins with a fall.</span></p><p><br></p><p><a href="https://surmon.me/" rel="noopener noreferrer" target="_blank" class="ql-font-serif ql-size-small" style="color: rgb(230, 0, 0);"><u>A ruler who hides behind paid executioners soon forgets what death is. </u></a></p><p><br></p><iframe class="ql-video ql-align-center" frameborder="0" allowfullscreen="true" src="https://www.youtube.com/embed/QHH3iSeDBLo?showinfo=0" height="238" width="560"></iframe><p><br></p><p><span class="ql-font-serif">Hear my words, and bear witness to my vow. Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the fire that burns against the cold, the light that brings the dawn, the horn that wakes the sleepers, the shield that guards the realms of men. I pledge my life and honor to the Nightâs Watch, for this night and all the nights to come.</span></p><p><br></p><p><span class="ql-font-serif">We are born to suffer, to suffer can make us strong.</span></p><p><br></p><p><span class="ql-font-serif">The things we love destroy us every time.</span></p>
        `,
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              [{ header: 1 }, { header: 2 }],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ script: "sub" }, { script: "super" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ size: ["small", false, "large", "huge"] }],
              [{ color: [] }, { background: [] }],
              [{ align: [] }],
              ["clean"],
              ["link", "image", "video"],
            ],
            handlers: {
              image() {
                self.uploadType = "image";
                self.showUploadDialog = true;
                let quill = self.$refs.myTextEditor.quill;
                // 获取光标所在位置
                self.insertPosition = quill.getSelection().index;
              },
              video() {
                self.uploadType = "video";
                self.showUploadDialog = true;
                let quill = self.$refs.myTextEditor.quill;
                // 获取光标所在位置
                self.insertPosition = quill.getSelection().index;
              },
            },
          },
        },
      },
      newsList: [],
      showDialog: false,
      form: {
        businessType: 1,
        messageId: -1,
        title: "",
        subTitle: "",
        imageId: "",
        detail: "",
        language: 1,
        imageId: "",
      },
      type: "ADD",
      total: 0,
      pageSize: 5,
    };
  },
  computed: {
    editor() {
      // return this.$refs.myTextEditor.quill;
    },
  },
  beforeMount() {
    // 只会在浏览器执行
    // this.$options.components.QuillEditor = () => import("vue-quill-editor");
  },
  created() {
    this.getList();
  },
  mounted() {},
  methods: {
    onConfirmInsertFile() {
      let quill = this.$refs.myTextEditor.quill;
      // 获取光标所在位置
      let uploadType = this.uploadType;
      let fileUrl = this.fileUrl;
      // 插入图片，res为服务器返回的图片链接地址
      quill.insertEmbed(
        this.insertPosition,
        uploadType,
        fileUrl
        // `https://pic3.zhimg.com/v2-f1fdd47221c0bcc8898daaea3880acd5_1440w.jpg?source=172ae18b`
      );
      // 调整光标到最后
      quill.setSelection(this.insertPosition + 1);
    },
    deleteImageSuccess() {
      this.form.imageId = "";
    },
    uploadImageSuccess() {},
    addVideoLink() {},
    onEditorChange(value) {
      this.content = value.html;
    },
    onEditorBlur(editor) {
      console.log("editor blur!", editor);
    },
    onEditorFocus(editor) {
      console.log("editor focus!", editor);
    },
    onEditorReady(editor) {
      console.log("editor ready!", editor);
    },
    async getList(current = 1) {
      await apiGetMessageList({ businessType: 1, current }).then((res) => {
        const data = res.data.data;
        this.newsList = res.data.data.records;
        this.total = data.total;
      });
    },
    // TODO:给后端图片，返imageId
    onUploadFile(params) {
      let file = params.file;
      let formData = new FormData();
      formData.append("file", file);
      formData.append("me");
      apiUploadImage(formData).then((res) => {
        this.$message.success("导入成功");
      });
    },
    onCurrentChange(currentPage) {
      this.getList(currentPage);
    },
    onAdd() {
      this.type = "ADD";
      this.form = {
        businessType: 1,
        messageId: -1,
        title: "",
        subTitle: "",
        imageId: "",
        detail: "",
        language: 1,
        imageId: "",
      };
      this.showDialog = true;
    },
    onEdit(scope) {
      this.type = "EDIT";
      Object.assign(this.form, scope.row);
      this.showDialog = true;
    },
    onDelete(scope) {
      this.$confirm("确认删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(async () => {
        await apiDeleteMessage({ messageId: scope.row.messageId });
        this.showDialog = false;
        this.getList();
      });
    },
    async onSave() {
      if (this.type === "ADD") {
        await apiAddMessage(this.form);
      } else {
        await apiUpdateMessage(this.form);
      }
      this.showDialog = false;
      this.getList();
    },
  },
};
</script>
<style lang="scss" scoped></style>
